package models

import (
	"github.com/jinzhu/gorm"
)

type Auth struct {
	Model

	Username string `json:"username"`
	Password string `json:"password"`
	Mobile   string `json:"mobile"`
}

// 登录
func CheckAuth(username, password string) (bool, int, error) {
	var auth Auth
	err := db.Select("id").Where(Auth{Username: username, Password: password}).First(&auth).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, auth.ID, err
	}

	if auth.ID > 0 {
		return true, auth.ID, nil
	}

	return false, auth.ID, nil
}

// 分页列表统计
func GetAuthsTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&Auth{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

// 分页列表
func GetAuths(pageNum int, pageSize int, maps interface{}) ([]*Auth, error) {
	var (
		auths []*Auth
		err   error
	)
	// 使用分页
	if pageNum > 0 && pageSize > 0 {
		err = db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&auths).Error
	} else { // 不分页
		err = db.Where(maps).Find(&auths).Error
	}
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return auths, nil
}

// 新增
func AddAuth(data map[string]interface{}) (int, error) {
	auth := Auth{
		Username: data["username"].(string),
		Password: data["password"].(string),
		Mobile:   data["mobile"].(string),
	}
	if err := db.Create(&auth).Error; err != nil {
		return -1, err
	}
	return auth.ID, nil
}

// 验证id是否存在
func ExistAuthByID(id int) (bool, error) {
	var auth Auth
	err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&auth).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if auth.ID > 0 {
		return true, nil
	}

	return false, nil
}

// 根据id查询账号
func GetAuth(id int) (*Auth, error) {
	var auth Auth
	err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&auth).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &auth, nil
}

// 修改
func EditAuth(id int, data interface{}) error {
	if err := db.Model(&Auth{}).Where("id = ? AND deleted_on = ? ", id, 0).Update(data).Error; err != nil {
		return err
	}
	return nil
}

// 删除
func DeleteAuth(id int) error {
	if err := db.Where("id = ? ", id).Delete(Auth{}).Error; err != nil {
		return err
	}
	return nil
}
